package com.android.lovely.ts

import android.graphics.drawable.BitmapDrawable
import android.util.Log
import coil.imageLoader
import coil.request.ImageRequest
import coil.size.Precision
import coil.transform.CircleCropTransformation
import com.android.lovely.ext.downloadFile
import com.android.lovely.manager.KVStore
import com.android.lovely.user.UserManager
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import com.kotlin.extensions.coroutine.applicationScope
import com.kotlin.extensions.dimen.Dimension.dp

class TSService : FirebaseMessagingService() {

    override fun onNewToken(token: String) {
        super.onNewToken(token)
        Log.e("TSService", "onNewFCMToken = $token")
        updateToken(token)
    }

    private fun updateToken(token: String) {
        if (token.isNotEmpty()) {
            KVStore.firebase = token
            if (UserManager.isLogin()) {
                applicationScope.launchSafety {
                    UserManager.updateAuth { fcmToken = token }
                }
            }
        }
    }

    override fun onMessageReceived(message: RemoteMessage) {
        super.onMessageReceived(message)
        if (UserManager.isB()) {
            val avatar = message.data["bot_avatar_url"]
            val request = ImageRequest.Builder(this).data(avatar).size(55.dp, 55.dp)
                .transformations(CircleCropTransformation())
                .precision(Precision.EXACT).target(onError = {
                    LovelyMsgHelper.show(message.data, null)
                }, onSuccess = { drawable ->
                    LovelyMsgHelper.show(message.data, (drawable as BitmapDrawable).bitmap)
                }).build()
            imageLoader.enqueue(request)
        }
    }


}